/*
 * File:   main.c (Potion Vial)
 * Author: danecj
 *
 * Created on April 5, 2014, 1:04 PM
 */
/*
 * Potion Colors:
 *  Heal(1) - Red (255,0,0)
 *  Envenom(2) - Green (10,250,10)
 *  PowerUp(3) - Orange (255,128,0)
 *  Damage(4) - EXPLOSION
 *
 * Ingredent Colors:
 *  Water(1) - Light Blue (47,230,234)
 *  Dragon Scale(2) - ??? Purple (128,0,128)
 *  Harpy Feather(3) - ??Yellow (255,255,0)
 *  Doxy Egg(4) - ??Light Yellow (255,255,55)
 *
 *
 */


#include <stdio.h>
#include <stdlib.h>
#include "PICconfig.h"
#include "RGB_TLC5947.h"
#include "IR_Send.h"
#include "RFID.h"
#include "sound.h"

#define BUTTON PORTCbits.RC5


int loop, potion;

void setupPIC (void);
void delay(unsigned int cycles);
void reset_all(void);
void startLED(void);

/*
 *
 */
void main() {
    // Delay to power PIC and RFID
    delay(30000);
    delay(30000);
    // Setup PIC
    setupPIC();
    delay(30000);
    delay(30000);
    // Setup UART for RFID
    initRFID();
    // Start TLC5940 LED Driver
    startTLC();
    startLED();
    // Reset GS Array
    all_off();
  
    while(1){
        int t = 0;
        // Set LED 0 to indicate PIC is on and powered
        setLED_ing(0,5);
        // Read potion from base station
        potion = readPotion();
        // Set LED 1 to indicate what potion is in vial
        setLED_potion(potion);

        // Wait for button to send IR and play sound
        while(!BUTTON){};
        // Play sound
        playPotionSong(potion);

        for(t=0;t<10;t++){
        // Send IR
        IR_Send(potion);
        delay(30000);
        }
        reset_all();
    };
}

void reset_all(void){
    all_off();
}

void setupPIC (void) {
        //Set Int-HF oscillator @ 16Mhz
        OSCCONbits.IRCF0=1;
	OSCCONbits.IRCF1=1;
	OSCCONbits.IRCF2=1;
        //Wait for Frequency
        while(OSCCONbits.HFIOFS != 1);
        //Set port directions
        //A0-A3 Outputs
        TRISAbits.TRISA0 = 0;
        TRISAbits.TRISA1 = 0;
        TRISAbits.TRISA2 = 0;
        TRISAbits.TRISA3 = 0;
        //C2 Output
        TRISCbits.TRISC2 = 0;
        //C5 Input
        TRISCbits.TRISC5 = 1;
        soundINIT();
        //Set all low
        //A0-A3 Low
	LATAbits.LATA0 = 0;
        LATAbits.LATA1 = 0;
        LATAbits.LATA2 = 0;
        LATAbits.LATA3 = 0;
        //B1 Low
        LATBbits.LATB1 = 0;
}

void delay( unsigned int cycles){
    for(loop = 0; loop < cycles; loop++);
}

void startLED(void){
    fade_on(0,255,0,0,100);
    fade_on(1,255,0,0,100);
    delay(10000);

    fade_on(0,0,255,0,100);
    fade_on(1,0,255,0,100);
    delay(10000);

    fade_on(0,0,0,255,100);
    fade_on(1,0,0,255,100);
    delay(10000);
}
